package com.mypog;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/UpdateHighscore")
public class UpdateHighscore extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/plain");
		PrintWriter out = response.getWriter();

		// Get highscore from DB.
		MySQLDb sql = new MySQLDb();
		String answer = sql.getSqlQuery(
				"SELECT * FROM Users ORDER BY Won DESC", "Name", "Won");
		out.print(answer);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		// Get user session.
		HttpSession session = request.getSession();
		String playerName = (String) session.getAttribute("username");

		// Get player.
		AllUsers allusers = new AllUsers();
		User player = allusers.getUserObject(playerName, "user");

		// Get status. (Won or Lost)
		String status = request.getParameter("status");

		// User won. Add +1.
		if (status.equals("won")) {
			won(player, playerName);

		}
		// User lost. Add +1.
		if (status.equals("lost")) {
			lost(player, playerName);
			
		}
	}
	// Update user and DB data.
	private void lost(User player, String playerName) {
		// Update user object.
		int number = Integer.parseInt(player.getLost()) + 1;
		player.setLost(Integer.toString(number));

		// Update DB.
		MySQLDb sql = new MySQLDb();
		sql.setSqlQyery("UPDATE Users SET Lost = "
				+ Integer.toString(number) + " WHERE Name = '"
				+ playerName + "'");		
	}

	// Update user and DB data.
	private void won(User player, String playerName) {
		// Update user object.
		int number = Integer.parseInt(player.getWon()) + 1;
		player.setWon(Integer.toString(number));

		// Update DB.
		MySQLDb sql = new MySQLDb();
		sql.setSqlQyery("UPDATE Users SET Won = " + Integer.toString(number)
				+ " WHERE Name = '" + playerName + "'");
	}

}
